<?php
namespace app\common\controller;

use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupRule;
use app\admin\model\AuthRule;
use think\Db;
use think\Controller;

class SysCommon extends Controller
{

    protected $model;                   //当前控制器关联模型
    protected $modelClass = false;      //数据模型命名空间


//    public function initialize()
//    {
/////dump(454545);die;
//        if(!session('manager_id')){
//            $this->redirect(url('Login/index'));
////            header("Location: ".url('Login/index'));
//        }
//
//
//        define('ISPJAX', request()->isPjax());
//        define('MODULE_NAME', request()->module());   //全小写
//        define('CONTROLLER_NAME', request()->controller());   //首字母大写
//        define('ACTION_NAME', request()->action());   //全小写
//
//        if (class_exists($this->modelClass)){
//            $this->model = new $this->modelClass;
//        }
//        //获取配置信息
//        $json_string = file_get_contents('menu.json');
//        $menu = json_decode($json_string, true);
//        $loginer = session('user_info');
//
//        //判断后台登录用户状态
//        $system_loginer_model = new Admin();
//        $where_status[] = ['id','eq',$loginer['id']];
//        $status = $system_loginer_model->findOne($where_status,"status");
//        if ($status != 1) {
//            if (request()->isPost()) {
//                echo ajax_return(0,'请重新登录');
//                exit;
//            } else {
//                $this->redirect(url('Login/index'));
//            }
//        }
//        $controller_name = strtolower(request()->controller());
//        $action_name = strtolower(request()->action());
//        //权限控制
//        $index = strpos($action_name, 'indep');
//        $auths = [];
//        $auths_group = [];
//        if ($loginer['rank'] != 1 && ($index === false || $index != 0)) {
//            $auth_rule_model=new AuthRule();
//            //获取角色授权id列表
//            $auth_group_rule_model=new AuthGroupRule();
//            $ruledata=$auth_group_rule_model->getIds($loginer['role_id']);
//            $where_auth[] = ['id','in',$ruledata];
//            $where_auth[] = ['type','neq',1];
//            $auths = $auth_rule_model->where($where_auth)->column('rule_url');
//            $group =$auth_rule_model->field('rule_val,group_name')->where($where_auth)->select();
//            $controller_group = [];
//
//            foreach ($group as $key => $value) {
//                $auths_group[] = $value['group_name'];
//                $controller_group[$value['group_name']][] = $value['rule_val'];
//            }
//            $auths_group=array_unique($auths_group);
//            foreach ($menu as $key => &$value) {
//                if (!in_array($value['group'], $auths_group)) {
//                    unset($menu[$key]);
//                } else {
//                    if (empty($value['_child'])) {    //只有一级
//                        if (!in_array($value['url'], $controller_group[$value['group']])) {
//                            unset($menu[$key]);
//                        }
//                        foreach ($value['_auth'] as $k3 => $v3) {
//                            if (!in_array($v3['url'], $controller_group[$value['group']])) {
//                                unset($menu[$key]['_auth'][$k3]);
//                            }
//                        }
//                    } else {
//                        foreach ($value['_child'] as $key1 => &$val) {
//                            if (!in_array($val['url'], $controller_group[$value['group']])) {
//                                unset($menu[$key]['_child'][$key1]);
//                            }
//                            foreach ($val['_auth'] as $k1 => $v1) {
//                                if (!in_array($v1['url'], $controller_group[$value['group']])) {
//                                    unset($menu[$key]['_child'][$key1]['_auth'][$k1]);
//                                    unset($menu[$key]['_child'][$key1]['_auth'][$k1]);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//
//            if (!(in_array($controller_name.'/'.ACTION_NAME, $auths))) {
//                if(!in_array(strtolower($controller_name.'/'.strtolower(request()->action())), ['index/index'])){
//                    if (request()->isPost()) {
//                        echo ajax_return(0,'未授权访问!');
//                        exit;
//                    } else {
//                        $this->error('未授权访问!');
//                    }
//                }
//            }
//        }
////        $group_name = '';
////        $auth_name = [];
////        foreach ($menu as $key1 => &$menu1) {
////            if (empty($menu1['_child'])) { //一级为最后一级
////
////                if ($controller_name == $menu1['group']) {
////                    $group_name = $menu1['url'];    //当前组和权限组
////                    $urls = array_column($menu1['_auth'], 'url');
////                    $auth_name = array_merge([$menu1['url']], $urls);
////                }
////            } else {
////
////                foreach ($menu1['_child'] as $key2 => &$menu2) {
////                    $urls = array_column($menu2['_auth'], 'url');
////                    $arr = array_merge([$menu2['url']], $urls);
////
////                    if ($controller_name == $menu1['group'] && in_array($action_name, $arr)) {
////                        $group_name = $menu2['url'];    //当前组和权限组
////                        $auth_name = $arr;
////                    }
////                }
////            }
////        }
//
//        $menu =array_values($menu);
//        $this->assign('menu', $menu);
//        $this->assign('loginer', $loginer);
//        $this->assign('auths', $auths);
//        $this->assign('controller_name', $controller_name);
//        $this->assign('auths_group', $auths_group);
//
//    }
//

    /*
     * 根据手机号获取 user_id
     * @string $phone  手机号
     */
    public function getUserId($phone)
    {
        $where['phone'] = $phone;
        $res = Db::name('user')->where($where)->find();
        return $res['id'];
    }


    /*
     * 处理积分
     * @string user_id  用户id
     * @string type     类型: 1 充值 , 2 提现 , 3 下注 , 4 中奖
     * @string integral 流水积分
     */
    public function integral($user_id,$type,$integral)
    {

        // 根据用户id 获取当前 余额
        $balance = $this->getBalance($user_id);

        // 设置基础数据
        $data['user_id']     = $user_id;
        $data['type']        = $type;
        $data['integral']    = $integral;
        $data['status']      = '1';
        $data['create_time'] = time();
        $data['update_time'] = time();

        //  类型:1 充值 , 2 提现 , 3 下注 , 4 中奖
        if($type == 1 || $type == 4){
            // 加上
            $data['balance'] = bcadd($balance,$integral,1);

        }elseif ($type == 2 || $type == 3){
            // 减去
            $data['balance'] = bcsub($balance,$integral,1);
        }

        // 插入数据库
        $res = Db::name('integral')->insert($data);
        if($res){
            return true;
        }else{
            return false;
        }

    }


    /*
     * 获取最新积分余额
     * @string $user_id  用户id
     */
    public function getBalance($user_id)
    {

        $where['user_id'] = $user_id;
        $res = Db::name('integral')->where($where)->order('id desc')->find();
        if($res){
            return $res['balance'];
        }else{
            return '0';
        }

    }

    /*
     *  修改状态
     */
    public function editStatus()
    {
        if(request()->isPost()){

            $post = input('post.');

//            $result = $this->validate($post, 'app\common\validate\\'.CONTROLLER_NAME.'.status');
//            if(true !== $result){
//                return ajax_return('0',$result);
//            }

            $result = $this->model->allowField(true)->where('id='.$post['id'])->update($post);
            if ($result){
                return ajax_return('1','操作成功');
            }else{
                return ajax_return('0',$this->model->getError());
            }
        }else{
            return ajax_return('0','FAIL');
        }

    }
    public function create()
    {
        if(request()->isPost()){
            $post = input('post.');
            //查验当前人的登录信息
            // 开启事务
            Db::startTrans();
            try{
                $res =$this->model->dataUpdate($post);
                if($res){
                    Db::commit();
                    return ajax_return('1','操作成功');
                }else{
                    Db::rollback();
                    return ajax_return('0','操作失败');
                }
            }catch (\Exception $e){
                Db::rollback();
                return  ajax_return('0',$e->getMessage());
            }

        }else{
            die('FAIL');
        }
    }
    /*
     * 修改
     */
    public function edit()
    {
        $post = input('post.');

        // 修改
        if(isset($post['undefined'])){
            unset($post['undefined']);
        }
        if(isset($post['id'])){
            $post['id'] = intval($post['id']);
        }
        $res = $this->model->dataUpdate($post);
        if(!$res){
            return ajax_return('0','操作成功');
        }
        return ajax_return('1','操作成功');
    }


    /*
     * 删除
     */
    public function delete()
    {

        $post = input('post.');
        $id = [];
        foreach ($post['id'] as $key=>$value){
            array_push($id,intval($value));
        }
        // 执行删除
        $res = $this->model->fieldUpdate('delete_time',time(),$id);

        if($res){
            return ajax_return('1','操作成功');
        }else{
            return ajax_return('0','操作失败');
        }
    }



}